package com.example.compose

import android.Manifest
import android.media.AudioFormat
import android.media.AudioRecord
import android.os.Build
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.isGranted
import com.google.accompanist.permissions.rememberPermissionState
import java.io.File
import java.io.FileInputStream

@Preview
@Composable
fun DialogPreview() {
    var showDialog by remember {
        mutableStateOf(false)
    }
    Column() {
        Button(onClick = { showDialog = !showDialog }) {
            Text("click show AlerDialog")
        }
        if (showDialog) {
            AlertDialog(
                onDismissRequest = {
                    showDialog = false
                },
                title = {
                    Text(text = "Title")
                },
                text = {
                    Text(
                        "This area typically contains the supportive text " +
                                "which presents the details regarding the Dialog's purpose."
                    )
                },
                confirmButton = {
                    TextButton(
                        onClick = {
                            showDialog = false
                        }
                    ) {
                        Text("Confirm")
                    }
                },
                dismissButton = {
                    TextButton(
                        onClick = {
                            showDialog = false
                        }
                    ) {
                        Text("Dismiss")
                    }
                }
            )
        }
    }


}

@Preview
@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun ReadFile() {

    Text(text = "急急急")
    var showDialog by remember {
        mutableStateOf(false)
    }

    val permissionState = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.TIRAMISU) {
        rememberPermissionState(Manifest.permission.READ_MEDIA_AUDIO)
    } else {
        rememberPermissionState(Manifest.permission.READ_EXTERNAL_STORAGE)
    }

    if (permissionState.status.isGranted) {
        Text(text = "权限已获取")
    } else {
        Button(onClick = { showDialog = !showDialog }) {
            Text(text = "按钮")
        }

        if (showDialog) {
            Dialog(onDismissRequest = { showDialog = !showDialog }) {
                Column(
                    modifier = Modifier
                        .size(200.dp, 50.dp)
                        .background(Color.White)
                ) {
                    Text(text = "这是一段描述Dialog内容的文本")
                    Button(onClick = { permissionState.launchPermissionRequest() }) {
                        Text(text = "确定")
                    }
                }
            }
//            AlertDialog(
//                onDismissRequest = { },
//                confirmButton = { /*permissionState.launchPermissionRequest() */ },
//                text = { Text(text = "需要读取文件,请同意获取权限") }
//            )
        }
    }
}

class AudioAnalyzer(private val filePath: String) {
    private val sampleRate = 44100
    private val bufferSize = AudioRecord.getMinBufferSize(
        sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT
    )
    private val byteArray = ByteArray(bufferSize)
    private val shortArray = ShortArray(bufferSize / 2)

    fun analyzeAudio(): FloatArray {
        val file = File(filePath)
        if (!file.exists()) {
            throw IllegalArgumentException("File does not exist")
        }

        val data = mutableListOf<Float>()
        val inputStream = FileInputStream(file)

        inputStream.use { input ->
            while (input.read(byteArray) != -1) {
                byteArrayToShortArray(byteArray, shortArray)
                val rms = calculateRMS(shortArray)
                data.add(rms)
            }
        }

        return data.toFloatArray()
    }

    private fun byteArrayToShortArray(byteArray: ByteArray, shortArray: ShortArray) {
        for (i in byteArray.indices step 2) {
            shortArray[i / 2] =
                (byteArray[i].toInt() and 0xFF or (byteArray[i + 1].toInt() shl 8)).toShort()
        }
    }

    private fun calculateRMS(shortArray: ShortArray): Float {
        var sum = 0.0
        for (value in shortArray) {
            sum += value * value
        }
        val rms = kotlin.math.sqrt(sum / shortArray.size)
        return rms.toFloat()
    }

    fun detectBeats(waveform: FloatArray, threshold: Float): List<Int> {
        val beats = mutableListOf<Int>()

        for (i in 1 until waveform.size - 1) {
            if (waveform[i] > waveform[i - 1] && waveform[i] > waveform[i + 1] && waveform[i] > threshold) {
                beats.add(i)
            }
        }

        return beats
    }
}
